package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;
    @Override
    public Member findMemberByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if(password != null){
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }

        memberDao.add(member);
    }

    @Override
    public List<Integer> findMemberCountByMonth(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month+".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }

        return memberCount;
    }

    @Override
    public void edit(Map map)throws Exception {
        // 获取名字
        String name = (String) map.get("name");
        String sex = (String) map.get("radio");
        String idCard = (String) map.get("idCard");
        String password = MD5Utils.md5((String) map.get("password"));
        String email = (String) map.get("email");
        String birthdayStr = (String) map.get("birthday");
        Date birthday = DateUtils.parseString2Date(birthdayStr);
        // 获取电话号码
        String telephone = (String) map.get("telephone");
        // 根据电话查找member
        Member member = memberDao.findByTelephone(telephone);
        member.setName(name);
        member.setSex(sex);
        member.setIdCard(idCard);
        member.setPassword(password);
        member.setEmail(email);
        member.setBirthday(birthday);
        memberDao.edit(member);
    }
}
